extends Global

var file = File.new()

func _ready():
	pass
func _in():
	._in()
	pass
	
#角色是否在场上, TODO
func inBattle(cha):
	return cha.get_parent() is TileMap
#给一个按钮添加快捷键
func addShotCutToBtn(btn, keys, showToolTip = true):
	var sc = ShortCut.new()
	var key = InputEventKey.new() 
	key.scancode = keys
	sc.set_shortcut(key)
	btn.shortcut = sc
	btn.shortcut_in_tooltip = showToolTip

#根据参数创建按钮
#baseNode: 此按钮需要被添加到的节点
#bindInstance: 此按钮需要绑定点击事件在哪个对象上
#text: 按钮文本, String
#callback: 点击事件回调函数名称, String
#args: 点击事件回调参数, String数组
#position: 按钮在父容器中的位置, Vector2
#shortCut：按钮的快捷键
#bindSelf：是否将按钮本身作为参数传入到回调中，若为true，则回调参数数组中的最后一个为按钮对象, boolean
func createItemButton(baseNode, bindInstance, text, callback, args=[], position = Vector2(90, 170), shortCut = null, bindSelf = false):
	var b = Button.new()
	b.name = text
	if position != null:
		b.rect_position = position
	b.text = text
	if bindSelf:
		args.append(b)
	b.connect("pressed", bindInstance, callback, args)
	baseNode.add_child(b)
	if shortCut != null:
		addShotCutToBtn(b, shortCut)
	return b

#创建图片按钮
#baseNode: 此按钮需要被添加到的节点
#bindInstance: 此按钮需要绑定点击事件在哪个对象上
#img: 按钮图片
#disabledImg: 按钮被禁用时的图片
#callback: 点击事件回调函数名称
#args: 点击事件回调参数
#position: 按钮在父容器中的位置
func createTextureButton(baseNode, bindInstance, img, disabledImg, callback, args=[], position = Vector2(90, 170)):
	var b = TextureButton.new()
	b.rect_position = position
	b.set_normal_texture(load(img))
	b.set_disabled_texture(load(disabledImg))
	b.connect("pressed", bindInstance, callback, args)
	baseNode.add_child(b)
	return b

#创建一个标签Label
func createLabel(text, baseNode):
	var lb = Label.new()
	lb.text = text
	baseNode.add_child(lb)
	return lb

#创建一个富文本标签RichTextLabel
func createRichTextLabel(text, baseNode, size = Vector2(580, 50), position = null):
	var lb = RichTextLabel.new()
	lb.bbcode_text = text
	lb.bbcode_enabled = true
	lb.push_align(0)
	lb.set_custom_minimum_size(size)
	lb.name = "RichTextLabel"
	baseNode.add_child(lb)
	if position != null:
		lb.rect_position = position
	return lb

#获得战场全部单元格cells TODO
func getAllCells():
	pass

#获得备战区全部角色 TODO
func getReadyChas():
	pass

#创建技能文字特效 TODO
func createSkillTextEff(text, position):
	var eff = sys.newEff("numHit", position, false, 1)
	eff.setText(text, "#FF0099")
	eff.anim.set_speed_scale(0.2)

#强制删除一个角色 TODO
func deleteCha(cha):
	pass

#创建窗口WindowDialog
func createWindowDialog(baseNode, title, size = Vector2(900, 500)):
	if not is_instance_valid(baseNode):return
	var window = WindowDialog.new()
	window.set_size(size)
	window.window_title = title
	baseNode.add_child(window)
	return window

#创建滚动容器ScrollContainer
func createScrollContainer(baseNode, size = null, position = null):
	var context = ScrollContainer.new()
	if size != null:
		context.set_custom_minimum_size(size)
	if position != null:
		context.rect_position = position
	baseNode.add_child(context)
	return context

#创建HBox
func createHBox(baseNode, position = null):
	var itemBox = HBoxContainer.new()
	baseNode.add_child(itemBox)
	if position != null:
		itemBox.rect_position = position
	return itemBox
	
#创建VBox
func createVBox(baseNode, position = null):
	var itemBox = VBoxContainer.new()
	baseNode.add_child(itemBox)
	if position != null:
		itemBox.rect_position = position
	return itemBox

#创建表格容器GridContainer
func createGridContainer(node, size, position = null):
	var taskBox = GridContainer.new()
	taskBox.columns = size
	node.add_child(taskBox)
	if position != null:
		taskBox.rect_position = position
	return taskBox

#创建输入框LineEdit
func createLineEdit(node, size):
	var taskBox = LineEdit.new()
	taskBox.set_custom_minimum_size(size)
	node.add_child(taskBox)
	return taskBox

#创建图片容器
func createTextureRect(path):
	var obj = TextureRect.new()
	obj.set_texture(load(path))
	return obj

#创建ImgBtn
func createImgBtn(path):
	var obj = ImgBtn.new()
	obj.set_texture(load(path))
	return obj
	
#获得文件类型，例如： "test.jpg"， 将返回"jpg"
func getFileType(file):
	var ext = file.split(".")
	if ext.size() < 2: 
		return null
	return ext[1]

#对字典指定字段进行加减
func dicPlus(dic, field, num):
	var f = dic.get(field)
	if f == null:
		dic[field] = num
	else:
		dic[field] = f + num

#从字典中进行检索，若没有则返回默认值
func dicGet(dic, field, default):
	var f = dic.get(field)
	if f == null:
		return default
	else:
		return f

#对字典指定字段进行append
func dicAppend(dic, field, obj):
	var f = dic.get(field)
	if f == null:
		dic[field] = [obj]
	else:
		dic[field].append(obj)
#将一个字符串转为Vector2
func stringToVector(cell):
	if cell is Vector2:return cell
	var x = int(cell.rsplit(",")[0].rsplit("(")[1])
	var y = int(cell.rsplit(",")[1].rsplit(")")[0])
	return Vector2(x, y)

#替换节点脚本
func changeScript(node, script):
	var prev_variables = {}
	var skip_variables = ["Script Variables", "script", "rect_global_position"]
	for property in node.get_property_list():
		var key = property.name
		if not key in skip_variables and key != "":
			prev_variables[key] = node.get(key)
	node.set_script(script)
	for property in prev_variables:
		node.set(property, prev_variables[property])	

#字符串转为数字
func str2num(txt):
	if txt == null or txt == "":
		return 0
	else:
		return int(txt)

#复制一个数组
func arrayCopy(list):
	var arrs = []
	for i in list:
		arrs.append(i)
	return arrs

func toJson(data):
	return JSON.parse(data).result

#返回两个位置之间的距离
func cellRan(v, cell):
	var x =  abs(cell.x - v.x)
	var y =  abs(cell.y - v.y)
	return x + y

#获得当前batDlg节点
func getBatDlg():
	pass

#获取玩家背包和队伍中的所有道具
func getPlayerTeamItemPck():
	var teamItemPck = ItemPck.new()
	for cha in sys.player.team.chas:
		var items = cha.eqps.items
		for item in items:
			if item != null:
				teamItemPck.addItem(item)

	var playerItems = sys.player.items.items
	for item in playerItems:
		if item != null:
			teamItemPck.addItem(item)
	return teamItemPck


#将道具置入角色中，成功返回true，没有空位了返回false
func pushItemToCha(item,chara):
	for i in chara.eqps.items.size():
		if chara.eqps.items[i] == null:
			chara.setEqp(item,i)
			return true 
	return false#获得当前BatDlg节点 TODO


var modNameCache = {}
	
func setModNameCache(id,modName):
	modNameCache[id] = modName 
	
func getModNameCache(id):
	if modNameCache.has(id) :
		return modNameCache[id]
	return null

	
func getModNameFromData(base):
	var id = base.id
	if getModNameCache(id):
		return getModNameCache(id)
		
	var dir = data.infoDs[id.split("_")[0]][id].dir
	if dir.split("/")[0] != "res:":
		print("未查询到MOD，base路径为",dir)
		return '未知MOD'
	var checkPath =  dir.split("/")[2]
		
	if checkPath == "ex" or checkPath == "ex2" or checkPath == "ex3" or checkPath == "!ve" or checkPath == "!vedo":
		setModNameCache(id, "原版")
		return "原版"

	var prePath = "res://" + checkPath + "/modInfo.gd"
	if ResourceLoader.exists(prePath):
		var mn = load(prePath).new().get("modName")
		if mn != null:
			setModNameCache(id, mn)
			return mn

	setModNameCache(id, "其他")
	return "其他"


#是否是箱庭地图模式
func isBoxMap():
	return is_instance_valid(sys.game) and sys.game.get("isBoxMap") != null
#打开一个JSON文件
func openJsonFile(path):
	if not file.file_exists(path):
		return null
	file.open(path, file.READ)
	return parse_json(file.get_as_text())

#创建对话框
func createTalkDlg(config):
	var dlg = load("res://!ve/base/tscn/talkDlg/talkDlg.tscn").instance()
	dlg.init(config)
	sys.main.ui.add_child(dlg)
	
#Att转字典
func toAttDs(att):
	var ds = {}
	ds["maxHp"] = att.maxHp
	ds["def"] = att.def
	ds["mdef"] = att.mdef
	ds["atk"] = att.atk
	ds["matk"] = att.matk
	ds["cri"] = att.cri
	ds["criR"] = att.criR
	ds["ran"] = att.ran
	ds["spd"] = att.spd
	ds["cdSpd"] = att.cdSpd
	ds["pen"] = att.pen
	ds["perAddDs"] = att.perAddDs
	ds["perMulDs"] = att.perMulDs
	return ds		
#字典转Att
func attFromDs(ds):
	var att = Att.new()
	att.maxHp = ds.get("maxHp", 0)
	att.def = ds.get("def", 0)
	att.mdef = ds.get("mdef", 0)
	att.atk = ds.get("atk", 0)
	att.matk = ds.get("matk", 0)
	att.cri = ds.get("cri", 0)
	att.criR = ds.get("criR", 0)
	att.ran = ds.get("ran", 0)
	att.spd = ds.get("spd", 0)
	att.cdSpd = ds.get("cdSpd", 0)
	att.pen = ds.get("pen", 0)
	att.perAddDs = ds.get("perAddDs", 0)
	att.perMulDs = ds.get("perMulDs", 0)
#检查玩家是否拥有出战的角色
func hasBattleCha():
	var bl = false
	for i in sys.player.team.chas:
		if i.cell.x < 5 :
			bl = true
			break
	return bl

#从角色身上移除该装备，装备会回到玩家装备池中
func delChaEqp(cha, item):
	var inx = findChaEqpIndex(cha, item)
	cha.eqps.delInxItem(inx)
	item.wearer = null
	if cha.team == sys.player.team and not item.get("once"):
		sys.player.items.addItem(item)

func findChaEqpIndex(cha, eqp):
	for i in cha.eqps.items.size():
		if cha.eqps.items[i] == eqp:
			return i
